package middle

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"shi_project/main/config"
	"time"
)

var (
	mySigningKey             = []byte("shiqiming")
	expiresTime  int64       = 600 //测试环境的过期时间
)

type MyCustomClaims struct {
	jwt.RegisteredClaims
}

func init() {
	if config.Env == "dev" {
		expiresTime = 1000000
	}
}
func ParseTokenGetInfo(tokenString string) (*MyCustomClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		// 验证签名方法是否正确
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return mySigningKey, nil
	})

	if err != nil {
		return nil, err
	}
	// 提取自定义声明
	if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
		return claims, nil
	}
	return nil, fmt.Errorf("invalid token")
}

func BuildToken(id string) string {
	claims := MyCustomClaims{
		// "bar",
		jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Second * time.Duration(expiresTime))),
			// ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Second * 10)),
			ID: id,
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	ss, err := token.SignedString(mySigningKey)
	if err != nil {
		fmt.Println("token自义加密失败")
	}
	return ss
}

func All() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method               //请求方法
		origin := c.Request.Header.Get("Origin") //请求头部
		if origin != "" {
			origin := c.Request.Header.Get("Origin")
			c.Header("Access-Control-Allow-Origin", origin)                                    // 这是允许访问所有域
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE") //服务器支持的所有跨域请求的方法,为了避免浏览次请求的多次'预检'请求
			//  header的类型
			c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
			//              允许跨域设置                                                                                                      可以返回其他子段
			c.Header("Access-Control-Expose-Headers", "Authorization,Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar") // 跨域关键设置 让浏览器可以解析
			c.Header("Access-Control-Max-Age", "172800")                                                                                                                                                                         // 缓存预检请求的时间，单位为秒，这里是两天// 缓存请求信息 单位为秒
			c.Header("Access-Control-Allow-Credentials", "false")                                                                                                                                                                //  跨域请求是否需要带cookie信息 默认设置为true
			// c.Header("Access-Control-Allow-Credentials", "http://localhost:8000")                                                                                                                                                  //  跨域请求是否需要带cookie信息 默认设置为true
			c.Set("content-type", "application/json")
			// c.Set("Authorization", "zhaoliu") // 设置返回格式是json
		}

		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.JSON(200, "Options Request!")
		}
		// 处理请求
		c.Next() //  处理请求
	}
}
func V1() gin.HandlerFunc {
	return func(c *gin.Context) {
		str, ok := c.Request.Header["Authorization"]
		if !ok {
			c.Abort()
			c.JSON(401, gin.H{
				"status": "401",
				"msg":    "无token",
			})
		} else {
			res, err := ParseTokenGetInfo(str[0])
			if err != nil {
				c.JSON(401, gin.H{
					"status": "401",
					"msg":    fmt.Sprintf("%s", err),
				})
				c.Abort()
			} else {
				freshToken := BuildToken(res.ID)
				c.Set("userId", res.ID)
				c.Header("Authorization", freshToken)
			}
		}
		c.Next()
	}
}
